import 'dart:async';
import 'dart:io';
import 'dart:math' as math;

import 'package:demo/constants/event_bus_key.dart';
import 'package:demo/constants/route_location.dart';
import 'package:demo/core/router/app_router_delegate.dart';
import 'package:demo/model/bean/event/page_destroy_bean.dart';
import 'package:demo/route/route_application.dart' show RouteStyle;
import 'package:demo/utils/connectivity.dart';
import 'package:demo/utils/crash_analysis.dart';
import 'package:demo/utils/dialog.dart';
import 'package:demo/utils/event_bus.dart';
import 'package:demo/utils/toast.dart';
import 'package:demo/widget/animation/circle_reaval.dart';
import 'package:demo/widget/animation/scale_animation.dart';
import 'package:demo/widget/dialog/bugly_upgrade_dialog.dart';
import 'package:flutter/material.dart';

class ExampleList extends StatefulWidget {
  const ExampleList({Key? key}) : super(key: key);

  @override
  _ExampleListState createState() => _ExampleListState();
}

class _ExampleListState extends State<ExampleList> {
  final ButtonStyle buttonStyle = TextButton.styleFrom(
    fixedSize: Size(160, 46),
    elevation: 10.0,
    backgroundColor: Colors.blue,
    primary: Colors.white,
    textStyle: const TextStyle(fontSize: 16, fontWeight: FontWeight.w700),
  );

  /// 页面销毁监听
  late final StreamSubscription<PageDestroyBean>? _streamSubscription;

  /// 升级弹窗
  late DialogUtils _dialogUtils = DialogUtils(context);

  @override
  void initState() {
    super.initState();
    _streamSubscription = EventBus.instance.monitoring<PageDestroyBean>(
      EVENT_BUS_PAGE_DESTROY_KEY,
      _onPageDestroyListener,
    );
    ConnectivityUtils.instance.monitoring("example_list", _onConnectivityListener);
    CrashAnalysisUtils.instance.setOnCheckUpgradeListener(_onCheckUpgradeListener);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      if (Platform.isAndroid) {
        CrashAnalysisUtils.instance.checkUpgrade();
      } else {
        _onCheckUpgradeListener(
          UpgradeInfo.fromJson({
            "newFeature": "1.优化了性能",
            "versionName": "1.0.1",
            "publishTime": 1625815415196,
            "upgradeType": 1,
          }),
        );
      }
    });
  }

  @override
  void dispose() {
    _dialogUtils.dismiss();
    _streamSubscription?.cancel();
    ConnectivityUtils.instance.unMonitor("example_list");
    super.dispose();
  }

  void _incrementCounter() async {
    _dialogUtils.show();
    // var res = await HttpClientDio.instance.get("${BuildConfig.shared.getMainHostUrl}$testApi");
    // LogUtils.instance.d(res.data);
    // _synchronizedLock.run(write1234);
    // _synchronizedLock.run(write1234);
    // _synchronizedLock.run(() async {
    //   write1234();
    // });
  }

  /// 升级监听
  void _onCheckUpgradeListener(UpgradeInfo info) {
    _dialogUtils.setLayoutWidget(
      BuglyUpgradeWidget(
        updateContent: info.newFeature!,
        versionName: info.versionName!,
        updateTimestamp: DateTime.fromMillisecondsSinceEpoch(info.publishTime!).toString(),
        onCancelClickListener: () {
          _dialogUtils.dismiss();
        },
        onUpgradeClickListener: () {
          _dialogUtils.dismiss();
        },
        isForce: info.upgradeType == 2,
      ),
    );
    _dialogUtils.show();
  }

  void _onPageDestroyListener(PageDestroyBean pageDestroyBean) {
    ToastUtils.showText(text: "收到 ${pageDestroyBean.name} 页面关闭的回调了");
  }

  /// 构建路由动画块
  Widget get _buildRouterAnimation {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Container(
          height: 58,
          alignment: Alignment.center,
          child: Text(
            "=====路由动画=====",
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700),
          ),
        ),
        Wrap(
          runSpacing: 12.0,
          spacing: 20,
          children: [
            ElevatedButton(
              style: buttonStyle,
              onPressed: () => AppRouterDelegate.of().push(EXAMPLE_MD_STYLE_LOCATION, style: RouteStyle.Android),
              child: Text("android跳转动画"),
            ),
            ElevatedButton(
              style: buttonStyle,
              onPressed: () => AppRouterDelegate.of().push(EXAMPLE_MD_STYLE_LOCATION, style: RouteStyle.IOS),
              child: Text("IOS跳转动画"),
            ),
            ElevatedButton(
              style: buttonStyle,
              onPressed: () => AppRouterDelegate.of().push(
                EXAMPLE_MD_STYLE_LOCATION,
                style: RouteStyle.Custom,
                customTransitionsBuilder: (
                  BuildContext context,
                  Animation<double> animation,
                  Animation<double> secondaryAnimation,
                  Widget child,
                ) {
                  return CircleReveal(
                    position: Offset(MediaQuery.of(context).size.width, MediaQuery.of(context).size.height),
                    revealPercent: animation.value,
                    child: child,
                  );
                },
              ),
              child: Text("自定义跳转动画"),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建列表类
  Widget get _buildListView {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Container(
          height: 58,
          alignment: Alignment.center,
          child: Text(
            "=====控件动画=====",
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700),
          ),
        ),
        Wrap(
          runSpacing: 12.0,
          spacing: 20,
          children: [
            ElevatedButton(
              style: buttonStyle,
              onPressed: () => AppRouterDelegate.of().push(EXAMPLE_FADE_STYLE_LIST_LOCATION),
              child: Text("淡入淡出偏移动画"),
            ),
            ElevatedButton(
              style: buttonStyle,
              onPressed: () {
                setState(() {});
              },
              child: Text("中央按钮缩放动画"),
            ),
          ],
        ),
      ],
    );
  }

  /// 控件类
  Widget get _buildWidgetGroup {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Container(
          height: 58,
          alignment: Alignment.center,
          child: Text(
            "======控件组======",
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700),
          ),
        ),
        Wrap(
          runSpacing: 12.0,
          spacing: 20,
          children: [
            ElevatedButton(
              style: buttonStyle,
              onPressed: () {},
              child: Text("底部悬浮按钮tab"),
            ),
            ElevatedButton(
              style: buttonStyle,
              onPressed: () => AppRouterDelegate.of().push(EXAMPLE_REFRESH_LOCATION),
              child: Text("无限list"),
            ),
            ElevatedButton(
              style: buttonStyle,
              onPressed: () {
                AppRouterDelegate.of().push(EXAMPLE_PICTURE_IN_PICTURE, style: RouteStyle.IOS);
              },
              child: Text("悬浮窗"),
            ),
          ],
        ),
      ],
    );
  }

  /// 项目类
  Widget get _buildApplicationGroup {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Container(
          height: 58,
          alignment: Alignment.center,
          child: Text(
            "======项目工程======",
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700),
          ),
        ),
        Wrap(
          runSpacing: 12.0,
          spacing: 20,
          children: [
            ElevatedButton(
              style: buttonStyle,
              onPressed: () => AppRouterDelegate.of().setRoot(ROOT_LOCATION),
              child: Text("项目案例"),
            ),
          ],
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("例子list"),
      ),
      body: ListView(
        children: [
          _buildApplicationGroup,
          _buildRouterAnimation,
          _buildListView,
          _buildWidgetGroup,
        ],
      ),
      bottomNavigationBar: SafeArea(
        bottom: true,
        child: BottomBarView(
          tabIconsList: TabIconData.tabIconsList,
          changeIndex: (int i) {},
          addClick: () {},
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.miniCenterDocked,
      floatingActionButton: ScaleAnimation(
        child: FloatingActionButton(
          onPressed: _incrementCounter,
          child: Icon(Icons.add),
        ),
      ),
    );
  }

  _onConnectivityListener(ConnectivityResult p1) {
    switch (p1) {
      case ConnectivityResult.wifi:
        ToastUtils.showText(text: "切换到wifi网络");
        break;
      case ConnectivityResult.mobile:
        ToastUtils.showText(text: "切换到移动网络");
        break;
      case ConnectivityResult.none:
        ToastUtils.showText(text: "没有网络");
        break;
    }
  }
}

class BottomBarView extends StatefulWidget {
  const BottomBarView({
    Key? key,
    required this.tabIconsList,
    required this.changeIndex,
    required this.addClick,
    this.containerHeight = 56,
  })  : assert(containerHeight > 0),
        super(key: key);

  final Function(int index) changeIndex;
  final Function addClick;
  final double containerHeight;
  final List<TabIconData> tabIconsList;

  @override
  _BottomBarViewState createState() => _BottomBarViewState();
}

class _BottomBarViewState extends State<BottomBarView> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: widget.containerHeight,
      child: PhysicalShape(
        color: Colors.white,
        clipper: TabClipper(radius: 38.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Expanded(
              child: Image.asset(widget.tabIconsList[0].selectedImagePath),
            ),
            Expanded(child: Image.asset(widget.tabIconsList[1].imagePath)),
            const SizedBox(width: 64.0),
            Expanded(
              child: Image.asset(
                widget.tabIconsList[2].imagePath,
              ),
            ),
            Expanded(child: Image.asset(widget.tabIconsList[3].imagePath)),
          ],
        ),
      ),
    );
  }
}

class TabClipper extends CustomClipper<Path> {
  TabClipper({this.radius = 38.0});

  final double radius;

  @override
  Path getClip(Size size) {
    final Path path = Path();
    final double v = radius * 2;
    final double left = (size.width / 2) - v / 2;
    path.arcTo(Rect.fromLTWH(0, 0, 0, 0), degreeToRadians(180), degreeToRadians(90), false);
    path.arcTo(
      Rect.fromLTWH(left - radius + v * 0.04, 0, radius, radius),
      degreeToRadians(270),
      degreeToRadians(70),
      false,
    );
    path.arcTo(Rect.fromLTWH(left, -v / 2, v, v), degreeToRadians(160), degreeToRadians(-140), false);
    path.arcTo(
      Rect.fromLTWH((size.width - left) - v * 0.04, 0, radius, radius),
      degreeToRadians(200),
      degreeToRadians(70),
      false,
    );
    path.arcTo(Rect.fromLTWH(size.width - radius, 0, 0, 0), degreeToRadians(270), degreeToRadians(90), false);
    path.lineTo(size.width, 0);
    path.lineTo(size.width, size.height);
    path.lineTo(0, size.height);
    path.close();
    return path;
  }

  @override
  bool shouldReclip(TabClipper oldClipper) => true;

  double degreeToRadians(double degree) => math.pi / 180 * degree;
}

class TabIconData {
  TabIconData({
    this.imagePath = '',
    this.index = 0,
    this.selectedImagePath = '',
    this.isSelected = false,
    this.animationController,
  });

  String imagePath;
  String selectedImagePath;
  bool isSelected;
  int index;

  AnimationController? animationController;

  static List<TabIconData> tabIconsList = <TabIconData>[
    TabIconData(
      imagePath: 'assets/tab/tab_1.png',
      selectedImagePath: 'assets/tab/tab_1s.png',
      index: 0,
      isSelected: true,
      animationController: null,
    ),
    TabIconData(
      imagePath: 'assets/tab/tab_2.png',
      selectedImagePath: 'assets/tab/tab_2s.png',
      index: 1,
      isSelected: false,
      animationController: null,
    ),
    TabIconData(
      imagePath: 'assets/tab/tab_3.png',
      selectedImagePath: 'assets/tab/tab_3s.png',
      index: 2,
      isSelected: false,
      animationController: null,
    ),
    TabIconData(
      imagePath: 'assets/tab/tab_4.png',
      selectedImagePath: 'assets/tab/tab_4s.png',
      index: 3,
      isSelected: false,
      animationController: null,
    ),
  ];
}
